package com.renjianbo.project.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.renjianbo.project.common.model.LoginUser;
import com.renjianbo.project.common.model.LoginUserStore;
import com.renjianbo.project.common.util.ExceptionUtil;
import com.renjianbo.project.common.util.JwtUtil;
import com.renjianbo.project.module.system.mapper.SysPermissionMapper;
import com.renjianbo.project.module.system.mapper.SysRolePermissionMapper;
import com.renjianbo.project.module.system.mapper.SysUserRoleMapper;
import com.renjianbo.project.module.system.model.sys_permission.SysPermissionDTO;
import com.renjianbo.project.module.system.model.sys_permission.SysPermissionSearchReq;
import com.renjianbo.project.module.system.model.sys_role_permission.SysRolePermissionDTO;
import com.renjianbo.project.module.system.model.sys_user_role.SysUserRole;
import com.renjianbo.project.module.system.model.sys_user_role.SysUserRoleDTO;
import com.renjianbo.project.module.system.model.sys_user_role.SysUserRoleSearchReq;
import org.springframework.beans.BeanUtils;
import com.renjianbo.project.module.system.model.sys_user.*;
import com.renjianbo.project.module.system.mapper.SysUserMapper;
import com.renjianbo.project.module.system.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.renjianbo.project.common.model.PageReq;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-用户 服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2022-05-20
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录
     */
    @Override
    public String login(SysUserLoginReq req) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, req.getAccount());
        queryWrapper.eq(SysUser::getIsDelete, 0);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(sysUser == null){
            ExceptionUtil.businessException("账号或密码错误");
        }
        if(!req.getPassword().equals(sysUser.getPassword())){
            ExceptionUtil.businessException("账号或密码错误");
        }

        return JwtUtil.createJWT(sysUser.getId());
    }

    /**
     * 用户详情
     */
    @Override
    public LoginUser userInfo() {
        Long userId = jwtUtil.getLoginUserId();

        //  用户角色
        List<Long> roleIdList = new ArrayList<>();
        //  开发者
        if(userId.equals(1L)){
            roleIdList.add(1L);
        //  普通用户
        } else {
            SysUserRoleSearchReq sysUserRoleSearchReq = new SysUserRoleSearchReq();
            sysUserRoleSearchReq.setUserId(userId);
            List<SysUserRoleDTO> sysUserRoleDTOList = sysUserRoleMapper.list(sysUserRoleSearchReq);
            roleIdList = sysUserRoleDTOList.stream().map(SysUserRoleDTO::getRoleId).collect(Collectors.toList());
        }

        //  用户权限
        List<Long> permissionIdList;
        List<String> permissionCodeList;
        //  开发者
        if(userId.equals(1L)){
            List<SysPermissionDTO> sysPermissionDTOList = sysPermissionMapper.list(new SysPermissionSearchReq());
            permissionIdList = sysPermissionDTOList.stream().map(SysPermissionDTO::getId).collect(Collectors.toList());
            permissionCodeList = sysPermissionDTOList.stream().map(SysPermissionDTO::getPermissionCode).collect(Collectors.toList());
        //  普通用户
        } else {
            List<SysRolePermissionDTO> rolePermissionDTOList = sysRolePermissionMapper.getRolePermissionByRoleId(roleIdList);
            permissionIdList = rolePermissionDTOList.stream().map(SysRolePermissionDTO::getPermissionId).collect(Collectors.toList());
            permissionCodeList = rolePermissionDTOList.stream().map(SysRolePermissionDTO::getPermissionCode).collect(Collectors.toList());
        }

        //  存储登录信息，可放入redis中
        LoginUserStore.userId = userId;
        LoginUserStore.roleIdList = roleIdList;
        LoginUserStore.permissionIdList = permissionIdList;
        LoginUserStore.permissionCodeList = permissionCodeList;

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userId);
        loginUser.setRoleIdList(roleIdList);
        loginUser.setPermissionIdList(permissionIdList);
        loginUser.setPermissionCodeList(permissionCodeList);

        return loginUser;
    }

    /**
    * 查询系统-用户分页数据
    */
    @Override
    public IPage<SysUserDTO> page(SysUserSearchReq req, PageReq pageReq){
        IPage<SysUserDTO> iPage = sysUserMapper.list(req, pageReq.getPage());

        return iPage;
    }

    /**
    * 新增系统-用户
    */
    @Override
    @Transactional
    public void add(SysUserAddReq req){
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(req, sysUser);
        sysUser.setPassword("123456");
        sysUserMapper.insert(sysUser);

        for (Long roleId: req.getRoleIdList()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    /**
    * 删除系统-用户
    */
    @Override
    @Transactional
    public void delete(Long id){
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setIsDelete((short) 1);

        sysUserMapper.updateById(sysUser);
    }

    /**
    * 更新系统-用户
    */
    @Override
    @Transactional
    public void update(SysUserUpdateReq req){
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(req, sysUser);
        sysUserMapper.updateById(sysUser);

        //  删除新数据
        LambdaUpdateWrapper<SysUserRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUserRole::getUserId, req.getId());
        sysUserRoleMapper.delete(updateWrapper);
        //  添加新数据
        for (Long roleId: req.getRoleIdList()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }

    /**
    * 根据id查询系统-用户
    */
    @Override
    public SysUserDTO getById(Long id){
        SysUserDTO sysUserDTO = sysUserMapper.getById(id);

        //  用户角色
        SysUserRoleSearchReq sysUserRoleSearchReq = new SysUserRoleSearchReq();
        sysUserRoleSearchReq.setUserId(id);
        List<SysUserRoleDTO> sysUserRoleDTOList = sysUserRoleMapper.list(sysUserRoleSearchReq);
        sysUserDTO.setRoleIdList(sysUserRoleDTOList.stream().map(SysUserRoleDTO::getRoleId).collect(Collectors.toList()));

        return sysUserDTO;
    }

}
